<template>
  <div style="background: #fff;width: 178px;height: 178px">
    <img v-if="props.modelValue" :src="props.modelValue" class="avatar" alt="" @click="drawer=true"/>
    <el-icon v-else class="avatar-uploader-icon" @click="drawer=true">
      <Plus/>
    </el-icon>
  </div>

  <el-drawer v-model="drawer" title="图库" :with-header="false">
    <el-upload class="avatar-uploader" :show-file-list="false" :on-change="onChange" :auto-upload="false">
      <img v-if="imageData.imgBase64" :src="imageData.imgBase64" class="avatar" alt=""/>
      <el-icon v-else class="avatar-uploader-icon">
        <Plus/>
      </el-icon>
    </el-upload>
    <el-divider border-style="dotted"/>
    <el-row :gutter="20">
      <el-col :span="6" v-for="(item, index) in imgList">
        <el-image style="width: 100px; height: 100px" :src="item.img" :preview-src-list="[item.img]"
                  @click="post(item.img)"/>
      </el-col>
    </el-row>
  </el-drawer>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref} from 'vue'
import {Plus} from '@element-plus/icons-vue'
import {tukuApi} from "@/api";
import {ElMessage} from "element-plus";

onMounted(() => {
  callImg()
})
const props = defineProps({modelValue: String})
const emit = defineEmits(['update:modelValue'])
const imgList = ref([])
const drawer = ref(false)
const imageData = reactive({
  imgBase64: '',
  imgName: ''
})
const onChange = (uploadFile: any, uploadFiles: any) => {
  let reader = new FileReader()
  reader.readAsDataURL(uploadFile.raw)
  reader.onload = () => {
    imageData.imgBase64 = reader.result
    imageData.imgName = uploadFile.name
    uploadImg()
  }
}

const uploadImg = () => {
  tukuApi.upload.call({name: imageData.imgName, base64: imageData.imgBase64}).then((res: any) => {
    if (res === 1) {
      ElMessage({
        showClose: true,
        message: '上传成功',
        type: 'success'
      })
      callImg()
      imageData.imgBase64 = ''
    }
  })
}
const callImg = () => {
  tukuApi.select.call().then((res: any) => {
    imgList.value = res
  })
}
//回显图片
const post = (imgUrl: any) => {
  emit('update:modelValue', imgUrl)
  drawer.value = false
}
</script>

<style scoped>
.avatar-uploader .avatar, .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
